package com.wash.shoes.domain.dy.util;

import com.ruoyi.common.utils.spring.SpringUtils;
import com.wash.shoes.common.property.DyProperty;
import lombok.extern.log4j.Log4j2;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

/**
 * @author lijianguo
 * @Date 27/03/2025 11:56
 * 请输入类的简介
 **/
@Log4j2
public class DySign {

    public static String getSignature(String method, String uri, long timestamp, String nonce, String body){

        DyProperty dyProperty = SpringUtils.getBean(DyProperty.class);
        try {
            return getSignature(dyProperty.getAppPrivateContent(), method, uri, timestamp, nonce, body);
        }catch (Exception e){
            log.error(e);
        }
        return null;
    }



    /**
     * @param privateKeyStr
     * @param method
     * @param uri
     * @param timestamp
     * @param nonce
     * @param body
     * @return 签名
     * @throws Exception
     */
    public static String getSignature(String privateKeyStr, String method, String uri, long timestamp, String nonce, String body) throws Exception {
        //method内容必须大写，如GET、POST，uri不包含域名，必须以'/'开头
        String rawStr = method + "\n" +
                uri + "\n" +
                timestamp + "\n" +
                nonce + "\n" +
                body + "\n";
        Signature sign = Signature.getInstance("SHA256withRSA");
        sign.initSign(string2PrivateKey(privateKeyStr));
        sign.update(rawStr.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(sign.sign());
    }

    /**
     * @param privateKeyStr 签名
     * @return
     */
    public static PrivateKey string2PrivateKey(String privateKeyStr) {
        PrivateKey prvKey = null;
        try {
            byte[] privateBytes = Base64.getDecoder().decode(privateKeyStr);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            prvKey = keyFactory.generatePrivate(keySpec);
        } catch (Exception ex) {
            log.error(ex);
        }
        return prvKey;
    }
}
